package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocal;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {

        //1.分页条件参数判断
        dto.checkParam();

        //2.用户判断
        if(WmThreadLocal.getWmUser()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //2.条件参数判断
        LambdaQueryWrapper<WmNews> queryWrapper=new LambdaQueryWrapper<>();
            //判断当前状态
            if(dto.getStatus()!=null){
                queryWrapper.eq(WmNews::getStatus,dto.getStatus());
            }

            //判断关键字
            if(!StringUtils.isEmpty(dto.getKeyword())){
                queryWrapper.like(WmNews::getTitle,dto.getKeyword());
            }

            //判断频道
        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

            //判断发布时间
        if(dto.getBeginPubdate()!=null && dto.getEndPubdate()!=null){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubdate(),dto.getEndPubdate());
        }

            //根据用户id查询
        Integer id = WmThreadLocal.getWmUser().getId();
        queryWrapper.eq(WmNews::getUserId,id);
            //排序，倒叙展示
        queryWrapper.orderByDesc(WmNews::getPublishTime);



        //3.开始执行分页查询
        IPage<WmNews> ipage=new Page<>(dto.getPage(),dto.getSize());

        ipage = page(ipage, queryWrapper);

        //4.封装数据
        ResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(),Integer.parseInt(ipage.getTotal()+""));
        result.setData(ipage.getRecords());

        return result;
    }

    /**
     * 发布文章，保存草稿，提交审核和修改
     *主方法
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) throws Exception {
        //1.参数判断
            //判断content文章内容不能为空
        if(dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1.5 如果type=-1的话，则暂时置空
        if(dto.getType()==-1){
            dto.setType(null);
        }


       //2.保存或者修改文章
        WmNews wmNews=new WmNews();
        BeanUtils.copyProperties(dto,wmNews);

        //封面图片
        if(dto.getImages().size()>0 && dto.getImages()!=null){
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }
        saveOrUpdateWmNews(wmNews);

        //如果是草稿
        if(dto.getStatus()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.CAO_GAO);
        }
        //2.5 抽取出内容中的图片地址集合
        List<String> contentImageList=chouquContentImage(dto);

        //3.文章与内容图片的关联
        saveWmNewsContentImage(wmNews,contentImageList, (short) 0);

        //4.文章与封面图片的关联
        saveWmNewsFengmianImage(wmNews,dto,contentImageList, (short) 1);

      /*  //异步调用自动审核业务
        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());*/

        wmNewsTaskService.saveNewsToTask(wmNews.getId().longValue(),wmNews.getPublishTime());




        return ResponseResult.okResult(AppHttpCodeEnum.SUBMIT_NEWS_SUCCESS);
    }



    /**
     * 第四个抽取方法，文章与封面图片的关联关系
     * 如果是自动的话，从内容图片去提取作为封面图片
     *  规则：
     *      如果内容中的图片个数是大于等于1小于3的话，则提取第一个作为封面图片，则是单图
     *      如果内容中的图片个数大于等于3的话，则提取前三张作为封面图片，则是多图
     *      如果内容中的图片个数为0，则认为是无图
     *
     */
    private void saveWmNewsFengmianImage(WmNews wmNews,WmNewsDto dto,List<String> contentImageList,Short type) {
        //1.获取封面图片地址
        List<String> images = dto.getImages();
        //如果是单图，三图，或者无图，则正常执行
        short newsType=0;
        //如果是自动的话，
        if(dto.getType()==null){
                //从内容中取出图片的操作
                if(contentImageList.size()>=1 && contentImageList.size()<3){
                    //单图，则取出第一张作为封面图片
                   images = contentImageList.stream().limit(1).collect(Collectors.toList());
                    newsType=1;
                }else if(contentImageList.size()>=3){
                    //多图，取出前三张作为封面图片
                  images=contentImageList.stream().limit(3).collect(Collectors.toList());
                    newsType=3;
                }else{
                    //无图
                    newsType=0;
                }
            //最后要更新wm_news表的文章布局
            wmNews.setImages(StringUtils.join(images,","));
            wmNews.setType(newsType);
            updateById( wmNews);
        }

        //最终也要执行中间表的新增
        saveWmNewsMaterial(wmNews,images,type);
    }


    /**
     * 第三个抽取方法，主要用来文章与内容的图片的关联关系
     * INSERT INTO wm_news_material (material_id,news_id,TYPE,ORD)
     * VALUES(1,1,1,1),(2,1,1,2),(3,1,1,3)
     * @param wmNews
     * @param contentImageList
     */
    private void saveWmNewsContentImage(WmNews wmNews, List<String> contentImageList,Short type) {
        saveWmNewsMaterial(wmNews, contentImageList,type);
    }

    /**
     * 抽取的第五个方法，专门用来新增中间表
     * @param wmNews
     * @param imageList
     */
    private void saveWmNewsMaterial(WmNews wmNews, List<String> imageList,Short type) {
        if(imageList !=null && imageList.size()>0){
            //2.6根据图片地址集合去查询wm_material表中对应的id
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                    Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageList));
            //2.7 获取相对应的素材id集合
            List<Integer> contentImageIdList = wmMaterials.stream().map(material -> material.getId()).collect(Collectors.toList());
            //1.批量新增wm_news_material表
            wmNewsMaterialMapper.saveRelations(contentImageIdList, wmNews.getId(), type);
        }
    }

    /**
     * 第二个抽取方法，从内容中抽取出图片地址的集合
     * @return
     */
    private List chouquContentImage(WmNewsDto dto) {

        List<String> contentImageList=new ArrayList<>();

        //1.获取文章内容
        String content = dto.getContent();
        //2.从内容中抽取图片集合
            //2.1 转换类型
        List<Map> contentList = JSONArray.parseArray(content, Map.class);
            //2.2遍历集合
        for (Map map : contentList) {
            if(map.get("type").equals("image")){
                String path = (String) map.get("value");
                contentImageList.add(path);
            }
        }
        return contentImageList;

    }

    /**
     * 抽取的第一个方法，保存或者修改wm_news表
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //封装数据用户id
        wmNews.setUserId(WmThreadLocal.getWmUser().getId());
        //创建时间
        wmNews.setCreatedTime(new Date());
        //提交时间
        wmNews.setSubmitedTime(new Date());
        //新增
        if(wmNews.getId()==null){
            //新增文章
            save(wmNews);
        }else{
            //修改
                //先删除文章素材中间表
                wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
                //修改文章
                updateById(wmNews);
        }
    }




    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.根据id查询文章
        WmNews wmNews = getById(dto.getId());

        //2.判断文章是否存在
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.SUBMIT_NEWS_NO);
        }

        //4修改文章enable
        wmNews.setEnable(dto.getEnable());
        updateById(wmNews);

        //5.发送消息
        kafkaTemplate.send("downOrUp_topic",JSON.toJSONString(wmNews));


        return ResponseResult.okResult("上下架成功");
    }
}
